package com.smart.service.impl;

import com.smart.entity.LoginUser;
import com.smart.entity.Toke;
import com.smart.entity.Users;
import com.smart.service.LoginService;
import com.smart.utils.JwtUtils;
import com.smart.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public Map<String, Object> login(Users user) {
        //        AuthenticationManager authenticate进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
//        System.out.println("aabbcc"+authenticate);
//        如果认证没通过给出对应提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败！");
        }
//        如果认证通过了，使用userid生成jwt，jwt存入Login
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUsers().getUid().toString();
        String jwt = JwtUtils.createJWT(userId);

        // 认证通过 存入 redis
        redisCache.setCacheObject("login:" + userId, loginUser);

        Users u = new Users();
        u.setRealname(loginUser.getUsers().getRealname());
        u.setSex(loginUser.getUsers().getSex());
        u.setTelephone(loginUser.getUsers().getTelephone());
        u.setBirthday(loginUser.getUsers().getBirthday());
        u.setAvatar(loginUser.getUsers().getAvatar());
        u.setStatus(loginUser.getUsers().getStatus());
        u.setUid(loginUser.getUsers().getUid());

        Map<String, Object> map = new HashMap<>();
        Toke toke = new Toke(jwt);
        map.put("token", toke.getToken());
        map.put("userInfo", u);

        return map;
    }
}
